package com.example.demo.web;

import com.alibaba.fastjson.JSONArray;
import com.example.demo.domain.Carousel;
import com.example.demo.services.CarouselServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;



@Controller
public class UploadController {
    @Autowired
    CarouselServer carouselServer;

    final String IMGPATH="static/img/";
    final String URLPATH="http://49.233.133.194/static/img/";


    @GetMapping("/upload")
    public String upload(Model model){
        model.addAttribute("carousel",new Carousel());
        return "upload";
    }
    @PostMapping("/upload/file")
    @ResponseBody
    public String fileUpload(@ModelAttribute Carousel carousel,@RequestParam("file") MultipartFile file){
        /*System.out.println(carousel.toString());Carousel{id=null, name='刘应杰', number='123', image_url='null', ownuser=123}*/

        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String fileName = file.getOriginalFilename();
        carousel.setImage_url(URLPATH+fileName);
        String uploadDir="";
        try {
            //获得项目部署的路径  来保存在静态文件上  E:/qq/springboot-learning-example-master/demo/target/classes/static/
            uploadDir=ResourceUtils.getURL("classpath:").getPath()+IMGPATH;
            File dest = new File(uploadDir + fileName);
            file.transferTo(dest);
            carouselServer.insertCarousel(carousel);
            System.out.println(uploadDir);
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败";
        }
        return "上传成功";
    }
    @ResponseBody
    @PostMapping("/upload/deleteAll")
    public String deleteAll(){
        try {
            carouselServer.deleteAll();
            return "删除成功";
        }catch (Exception e){
            return "删除失败";
        }
    }
    @GetMapping("/upload/selectAll")
    @ResponseBody
    public String selectAll(){
        Object json = JSONArray.toJSON(carouselServer.fieldAll());
        return json.toString();
    }

}
